<?php

namespace app\admin\controller\jdy;

use app\common\controller\Backend;

use app\admin\library\Auth;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

use think\Log;


use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\IWriter;
//use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;


use fast\Http;

/**
 * 案場信息管理
 *
 * @icon fa fa-circle-o
 */
class Anchang extends Backend
{

    /**
     * Anchang模型对象
     * @var \app\admin\model\jdy\Anchang
     */
    protected $model = null;

    protected $noNeedRight = ['selectpage2', 'cxselect', 'importnew', 'changelog', 'gzrl'];

    protected $isadmin = false;//

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\jdy\Anchang;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("feeTypeList", $this->model->getFeeTypeList());

        $this->assignconfig('op1', $this->auth->check('jdy/device/index'));
        $this->assignconfig('op2', $this->auth->check('jdy/acdevice/index'));
        $this->assignconfig('op3', $this->auth->check('jdy/sdbiao/index'));
        $this->assignconfig('op4', $this->auth->check('jdy/task/index'));
        $this->assignconfig('op5', $this->auth->check('jdy/anchanglog/index'));
        $this->assignconfig('op6', $this->auth->check('jdy/feelog/index'));
        $this->assignconfig('op7', $this->auth->check('jdy/maintenance/index'));
        $this->assignconfig('op8', $this->auth->check('jdy/heyue/index'));

        $group_ids = $this->auth->getGroupIds();
        if (in_array("2", $group_ids) || in_array("1", $group_ids)) {
            $this->isadmin = true;//管理员权限不考虑管辖区域
        }
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $anchangids = $this->getanchangids();

            $whereA = "";
            if (!$this->isadmin) {
                if (empty($anchangids)) {
                    $whereA = " anchang.id  = 0 ";
                } else {
                    $whereA = " anchang.id in (" . $anchangids . ") ";
                }
            }

            $total = $this->model
                ->with(['building', 'room'])
                ->where($where)
                ->where($whereA)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['building', 'room'])
                ->where($where)
                ->where($whereA)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            foreach ($list as &$row) {
                if ($row->room_id == 0) {
                    $room = \app\admin\model\jdy\Room::with(['building'])->where('building.remark', $row->remark)->find();
                    if ($room) {
                        $row->building_id = $room->building['id'];
                        $row->room_id = $room->id;
                        $row->save();
                    }
                }
            }
            $list = collection($list)->toArray();
            foreach ($list as &$row) {
                if (intval($row['companywindow_id']) > 0) {
                    $admin = \app\admin\model\Admin::get($row['companywindow_id']);
                    if ($admin) {
                        $row['companywindow_name'] = $admin->nickname;
                    }
                }

            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if (empty($params['pay_date'])) {
                    unset($params['pay_date']);
                }
                if (empty($params['orderdate'])) {
                    unset($params['orderdate']);
                }

                if (!empty($params['addr'])) {
                    $address = $params['addr'];
                    $url = "http://zipcode.mosky.tw/api/find?address=" . $address;
                    $data = Http::get($url);
                    $ret = json_decode($data, TRUE);
                    if ($ret['result']) {
                        $zipcode = $ret['result'];
                        if (!empty($zipcode)) {
                            $zcode = \app\admin\model\jdy\Zipcodenum::where('zipcode', $zipcode)->find();
                            if (!$zcode) {
                                $zcode = new \app\admin\model\jdy\Zipcodenum();
                                $zcode->zipcode = $zipcode;
                                $zcode->num = 1;
                            } else {
                                $zcode->num = $zcode->num + 1;
                            }
                            $zcode->save();
                            $params['remark'] = $zipcode . "-" . $zcode->num;
                        }
                    }

                    $params['mapurl'] = "http://maps.google.com.tw/maps?f=q&hl=zh-TW&geocode=&q=".$address;
                }

                if (!empty($params['xianshi']) && !empty($params['xzq'])) {
                    $xianshi_pre = mb_substr($params['xianshi'], 0, mb_strlen($params['xianshi']) - 1);
                    $xzq_pre = mb_substr($params['xzq'], 0, mb_strlen($params['xzq']) - 1);
                    $name_pre = $xianshi_pre . $xzq_pre;
                    if (strpos($params['name'], $name_pre) === false) {
                        $params['name'] = $name_pre . $params['name'];
                    }
                }

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if (empty($params['pay_date'])) {
                    unset($params['pay_date']);
                }
                if (empty($params['orderdate'])) {
                    unset($params['orderdate']);
                }
                $pre = json_encode($row);
                $next = json_encode($params);

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $alog = new \app\admin\model\jdy\Anchanglog();
                    $alog->anchang_id = $row->id;
                    $alog->pre = $pre;
                    $alog->next = $next;
                    $alog->opman = $this->auth->nickname;
                    $alog->save();

                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function cxselect()
    {
        $type = $this->request->get('type', '');
        $xianshi = $this->request->get('xianshi', '');

        $list = null;
        if ($type == 'xianshi') {
            $sql = "select name as value, name from city WHERE 1";
            $list = Db::query($sql);
        } else if ($xianshi !== '') {
            $sql = "select t.name as value, t.name as name from town t INNER JOIN city c on t.city_code=c.code WHERE c.name= '" . $xianshi . "'";
            $list = Db::query($sql);
        }

        $this->success('', null, $list);
    }

    //http://acciot.test/admin/jdy/anchang/importnew
    //导出新建
    public function importnew()
    {
        $count = $this->model
            ->where('room_id', 0)
            ->count();

        if ($count < 1) {
//            echo '无新建案场';
//            $this->success('无新建案场');
//            exit();
        }

        set_time_limit(0);
        ini_set('memory_limit', '128M');

        header('Content-Type: application/vnd.ms-execl');
        header('Content-Disposition: attachment;filename="新建案场.csv"');

        //打开php标准输出流
        //以写入追加的方式打开
        $fp = fopen('php://output', 'a');
        //一次取5000条数据
        $step = ceil($count/5000);

        $chartset = 'GBK';//'GBK';//BIG5
        $title = array(
            iconv('UTF-8', $chartset, '案場名称'),
            iconv('UTF-8', $chartset, '案場地址'),
            iconv('UTF-8', $chartset, '案場编号'),
            iconv('UTF-8', $chartset, '楼层数')
        );

        //将标题写到标准输出中
        fputcsv($fp, $title);

        for($s = 0; $s < $step; $s++) {
            $page_count = $s;
            $page_size = 5000;
            $offset = $page_count * $page_size;
            $list = $this->model
                ->where('room_id', 0)
                ->select();
            $data = collection($list)->toArray();

            foreach ($data as &$row) {
                try {
                    $row['name'] = iconv('UTF-8', $chartset, $row['name']);
                    $row['addr'] = iconv('UTF-8', $chartset, $row['addr']);
                    $row['remark'] = iconv('UTF-8', $chartset, $row['remark']);
                    $row['floor_no'] = iconv('UTF-8', $chartset, $row['floor_no']);
                    $v = array(
                        $row['name'],
                        $row['addr'],
                        $row['remark'],
                        $row['floor_no']
                    );

                    fputcsv($fp, $v);
                } catch (\Exception $e) {
                    continue;
                }
            }
            //每5000条数据就刷新缓冲区
            ob_flush();
            flush();
        }
        exit();

    }

    public function changelog() {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['building','room'])
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['building','room'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            foreach ($list as &$row) {
                if ($row->room_id == 0) {
                    $room = \app\admin\model\jdy\Room::with(['building'])->where('building.remark', $row->remark)->find();
                    if ($room) {
                        $row->building_id = $room->building['id'];
                        $row->room_id = $room->id;
                        $row->save();
                    }
                }
            }
            $list = collection($list)->toArray();
            foreach ($list as &$row) {
                if (intval($row['contact1_id']) > 0) {
                    $contact1 = \app\admin\model\jdy\Contact::get($row['contact1_id']);
                    if ($contact1) {
                        $row['contact1_name'] = $contact1->name;
                        $row['contact1_mobile'] = $contact1->mobile;
                    }
                }
                if (intval($row['contact2_id']) > 0) {
                    $contact2 = \app\admin\model\jdy\Contact::get($row['contact2_id']);
                    if ($contact2) {
                        $row['contact2_name'] = $contact2->name;
                        $row['contact2_mobile'] = $contact2->mobile;
                    }
                }
                if (intval($row['companywindow_id']) > 0) {
                    $admin = \app\admin\model\Admin::get($row['companywindow_id']);
                    if ($admin) {
                        $row['companywindow_name'] = $admin->nickname;
                    }
                }

            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function selectpage2()
    {
        $this->dataLimitField = 'id';
        return parent::selectpage();
    }

    public function gzrl()
    {
        $searchtime = $this->request->get('searchtime', date("Y-m"));

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $searchtime = $params['searchtime'];
                $this->success("设置查询时间成功！", 'gzrl?searchtime='.$searchtime);
            }
        }

        $start = date("Y-m-d", strtotime($searchtime));//本月初
        $end = date("Y-m-d", strtotime("+1 month", strtotime($searchtime)));//次月初

        $anchangids = $this->getanchangids();

        $whereA = "";
        if (!$this->isadmin) {
            if (empty($anchangids)) {
                $whereA = " anchang_id  = 0 ";
            } else {
                $whereA = " anchang_id in (" . $anchangids . ") ";
            }
        }

        $taskmodel = new \app\admin\model\jdy\Task();

        //选择月待處理
        $num0 = $taskmodel->where($whereA)->where("task_status", "<>", "已結案")->where("remind_date", ">=", $start)->where("remind_date", "<", $end)->count();

        //已結案
        $num1 = $taskmodel->where($whereA)->where("task_status", "已結案")->where("remind_date", ">=", $start)->where("remind_date", "<", $end)->count();

        $this->view->assign("num0", $num0);
        $this->view->assign("num1", $num1);

        //所有的
        $tasklist = $taskmodel->where($whereA)->field("id, title,anchang_id, task_status, remind_date")->select();
        $list = [];
        foreach ($tasklist as $row) {
            $anchang = \app\admin\model\jdy\Anchang::get($row->anchang_id);
            $anchangname = "";
            if ($anchang) {
                $anchangname = $anchang->name;
            }
            $list[] = array(
                "title" => "(".$anchangname.") ".$row->title,
                "detail" => "=>" . $row->task_status,
                "datetime" => $row->remind_date,
                "id" => $row->id
            );
        }
        $this->view->assign("list", $list);

        $this->view->assign("searchtime", $searchtime);
        $searchyear = date("Y", strtotime($searchtime));
        $this->view->assign("searchyear", $searchyear);
        return $this->view->fetch();
    }

    public function getanchanglist()
    {
        $anchangidlist = json_decode($this->auth->anchangids, TRUE);
        $xianshi = [];
        $xianshi[] = $this->auth->xianshi1;
        $xianshi[] = $this->auth->xianshi2;
        $xianshi[] = $this->auth->xianshi3;
        $xianshi[] = $this->auth->xianshi4;
        $xianshi[] = $this->auth->xianshi5;

        $xzq = [];
        $xzq[] = $this->auth->xzq1;
        $xzq[] = $this->auth->xzq2;
        $xzq[] = $this->auth->xzq3;
        $xzq[] = $this->auth->xzq4;
        $xzq[] = $this->auth->xzq5;

        $xianshis = "";//只有市
        $xianshisA = "";
        for ($i = 0; $i < 5; $i++) {
            if (!empty($xianshi[$i]) && empty($xzq[$i])) {
                if (empty($xianshis)) {
                    $xianshis = $xianshi[$i];
                    $xianshisA = "'" . $xianshis . "'";
                } else if (strpos($xianshis, $xianshi[$i]) === false) {
                    $xianshis .= ',' . $xianshi[$i];
                    $xianshisA .= ",'" . $xianshi[$i] . "'";
                }
            }
        }

        $xzqs = "";//
        $xzqsA = "";//
        for ($i = 0; $i < 5; $i++) {
            if (!empty($xzq[$i]) && !empty($xianshi[$i]) && strpos($xianshis, $xianshi[$i]) === false) {
                if (empty($xzqs)) {
                    $xzqs = $xzq[$i];
                    $xzqsA = "'" . $xzqs . "'";
                } else if (strpos($xzqs, $xzq[$i]) === false) {
                    $xzqs .= ',' . $xzq[$i];
                    $xzqsA .= ",'" . $xzq[$i] . "'";
                }
            }
        }

        $whereA = "";
        if (!empty($xianshis)) {
            $whereA = " xianshi in (" . $xianshisA . ") ";
        }

        if (!empty($xzqs)) {
            if (!empty($whereA)) {
                $whereA .= " or ";
            }
            $whereA .= " xzq in (" . $xzqsA . ") ";
        }

        $anchangids = "";//"117,116"
        if ($anchangidlist) {
            foreach ($anchangidlist as $row) {
                if (empty($anchangids)) {
                    $anchangids = $row['id'];
                } else {
                    $anchangids .= ',' . $row['id'];
                }
            }
        }

        if (!empty($anchangids)) {
            if (!empty($whereA)) {
                $whereA .= " or ";
            }
            $whereA .= " id in (" . $anchangids . ") ";
        }

        $list = [];
        if (!empty($whereA)) {
            $list = \app\admin\model\jdy\Anchang::where($whereA)->select();
        }

        return $list;
    }

    public function getanchangids() {
        $anchangidlist = $this->getanchanglist();
        $anchangids = "";
        foreach ($anchangidlist as $row) {
            if (empty($anchangids)) {
                $anchangids = $row['id'];
            } else {
                $anchangids .= ',' . $row['id'];
            }
        }
        return $anchangids;
    }

}
